#!/opt/homebrew/bin/bash

ACCESS_OUTDATED_DAYS=180
# ======================= Maven
MAVEN_REPO="$HOME/.m2/repository"
if [ -d "$MAVEN_REPO" ]; then
  echo "----【maven 仓库】删除 $ACCESS_OUTDATED_DAYS 天未访问的版本"
  mapfile -t maven_clean_files < <(find "$MAVEN_REPO" -name "*.pom" -type f -atime +"$ACCESS_OUTDATED_DAYS")
  for f in "${maven_clean_files[@]}"; do
    mf=${f%/*}
    if test -d "$mf"; then
      echo "$mf"
      trash -Fv "${mf}"
    fi
  done

  # echo "----【maven 仓库】删除快照"
  # find "$MAVEN_REPO" -path "*-SNAPSHOT" -type d -exec trash -Fv {} +

  # echo "----【maven 仓库】删除 rc"
  # find "$MAVEN_REPO" -iregex ".*/[0-9].*[-.]rc[0-9]*" -type d -exec trash -Fv {} +

  # echo "----【maven 仓库】删除 beta"
  # find "$MAVEN_REPO" -iregex ".*/[0-9].*[-.]beta[0-9]*" -type d -exec trash -Fv {} +

  #echo "----【maven 仓库】删除 alpha"
  #find "$MAVEN_REPO" -iregex ".*/[0-9].*[-.]alpha[0-9]*" -type d -exec trash -Fv {} +

  echo "----【maven 仓库】删除 unknown"
  find "$MAVEN_REPO" -path "*/unknown" -type d -exec trash -Fv {} +

  echo "----【maven 仓库】删除 lastUpdated"
  find "$MAVEN_REPO" -name "*.lastUpdated" -type f -exec trash -Fv {} +

  echo "----【maven 仓库】删除 ~/.m2/repository/demo"
  [ -d "$MAVEN_REPO/demo" ] && trash -Fv "$MAVEN_REPO/demo"

  echo "----【maven 仓库】删除 .DS_Store"
  find "$MAVEN_REPO" -name ".DS_Store" -delete

  echo "----【maven 仓库】删除空文件&文件夹"
  find "$MAVEN_REPO" -empty -exec trash -Fv {} +
fi

# ===================== gradle
GRADLE_CACHE="$HOME/.gradle/caches"
if [ -d "$GRADLE_CACHE" ]; then
  echo "----【gradle 仓库】删除 $ACCESS_OUTDATED_DAYS 天未访问的版本"
  mapfile -t gradle_clean_files < <(find "$GRADLE_CACHE"/modules-2/files-2.1 -name "*.pom" -type f -atime +"$ACCESS_OUTDATED_DAYS")
  for f in "${gradle_clean_files[@]}"; do
    # 上上级2次
    mf=${f%/*}
    mf=${mf%/*}
    if [[ ! $mf =~ (com\.jetbrains\.intellij\.idea) ]]; then
      if test -d "$mf"; then
        echo "$mf"
        trash -Fv "${mf}"
      fi
    fi
  done

  # echo "----【gradle 缓存】删除快照"
  # find "$GRADLE_CACHE" -path "*-SNAPSHOT" -type d -exec trash -Fv {} +

  #echo "----【gradle 缓存】删除 rc"
  #find "$GRADLE_CACHE" -iregex ".*/[0-9].*[-.]rc[0-9]*" -type d -exec trash -Fv {} +

  #echo "----【gradle 缓存】删除 beta"
  #find "$GRADLE_CACHE" -iregex ".*/[0-9].*[-.]beta[0-9]*" -type d -exec trash -Fv {} +

  #echo "----【gradle 缓存】删除 alpha"
  #find "$GRADLE_CACHE" -iregex ".*/[0-9].*[-.]alpha[0-9]*" -type d -exec trash -Fv {} +

  echo "----【gradle 仓库】删除 .DS_Store"
  find "$GRADLE_CACHE" -name ".DS_Store" -delete

  echo "----【gradle 仓库】删除空文件&文件夹"
  find "$GRADLE_CACHE" -empty -exec trash -Fv {} +
fi

echo "----【pnpm  清理】pnpm store prune"
pnpm store prune

echo "----【brew  清理】brew cleanup"
brew cleanup --prune=all